//
//  CustomPickerView.m
//  BSNL_Market
//
//  Created by ayi on 2018/5/10.
//  Copyright © 2018 ayi. All rights reserved.
//

#import "CustomPickerView.h"

@interface CustomPickerView()<UIPickerViewDelegate,UIPickerViewDataSource>

@property (nonatomic, strong) UIView *bgView;;
@property (nonatomic, strong) UIButton *bgBtn;
@property (nonatomic, strong) UILabel *titleLab;
@property (nonatomic, strong) UIButton *sureBtn;
@property (nonatomic, strong) UIButton *cancelBtn;
@property (nonatomic, copy) NSArray *dataAry;
@property (nonatomic, copy) id chooseAry;

@property (nonatomic, strong) NSArray *data2Ary;

@end

@implementation CustomPickerView

- (void)dealloc{
    self.picker = nil;
    self.datepicker = nil;
    NSLog(@"=========%@", NSStringFromClass(self.class));
}

+ (instancetype)initWithFrame:(CGRect)frame
                 withModeType:(PickerViewMode)type
                  andTitleLab:(NSString *)titleStr
                 componentAry:(NSArray *)ary
                 andHasChoose:(id )chooseData
                  andCallBack:(pickerCallBack)resultblock{
    CustomPickerView *picker = [[CustomPickerView alloc] initWithFrame:frame withModeType:type andTitleLab:titleStr componentAry:ary andHasChoose:chooseData];
    picker.resultBlock = resultblock;
    [picker showInView];
    return picker;
}

- (instancetype)initWithFrame:(CGRect)frame withModeType:(PickerViewMode)type andTitleLab:(NSString *)titleStr componentAry:(NSArray *)ary andHasChoose:(id )chooseData
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        self.viewMode = type;
        self.titleLab.text = titleStr;
        self.dataAry = ary;
        if (self.viewMode == CustomConfirmOrderTimePicker) {
            self.data2Ary = ary[1][0];
        }
        self.chooseAry = chooseData;
        [self initDatePickerInView];
    }
    return self;
}

- (void)initDatePickerInView{
    [self addSubview:self.bgBtn];
    [self addSubview:self.bgView];
    self.bgView.frame = CGRectMake(0, BOUNDHEIGHT, BOUNDWIDTH, 216 + 45);
    self.bgBtn.frame = CGRectMake(0, 0, BOUNDWIDTH, BOUNDHEIGHT);
    
    UIView *titleView = [[UIView alloc]init];
    titleView.backgroundColor = [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1.0];
    [titleView addSubview:self.titleLab];
    [titleView addSubview:self.cancelBtn];
    [titleView addSubview:self.sureBtn];
    
    titleView.frame = CGRectMake(0, 0, BOUNDWIDTH, 42);
    [_bgView addSubview:titleView];
    
    _cancelBtn.frame = CGRectMake(0, 0, 45, CGRectGetHeight(titleView.frame));
    _sureBtn.frame = CGRectMake(BOUNDWIDTH- 45, 0, 45, CGRectGetHeight(titleView.frame));
    _titleLab.frame = CGRectMake(0, 0, BOUNDWIDTH, CGRectGetHeight(titleView.frame));
    
    if (self.viewMode == DatePicker) {
        [self.bgView addSubview:self.datepicker];
        self.datepicker.frame = CGRectMake(0, CGRectGetMaxY(titleView.frame), BOUNDWIDTH, 216);
    }else{
        [self.bgView addSubview:self.picker];
        self.picker.frame = CGRectMake(0, CGRectGetMaxY(titleView.frame), BOUNDWIDTH, 216);
    }
    [self selectPickerWithRow];
}
- (void)selectPickerWithRow{
    if (self.chooseAry == nil) {
        return;
    }
    if (self.viewMode == DatePicker) {
        [self.datepicker setDate:self.chooseAry];
    }
    if (self.viewMode == CustomPicker) {
        [self.picker reloadAllComponents];
        for (int i = 0; i< ((NSArray *)self.chooseAry).count;i ++) {
            if ([self.dataAry[i] indexOfObject:self.chooseAry[i]] != NSNotFound) {
                [self.picker selectRow:[self.dataAry[i] indexOfObject:self.chooseAry[i]] inComponent:i animated:NO];
            }
        }
    }
    if (self.viewMode == CustomConfirmOrderTimePicker) {
        [self.picker reloadAllComponents];
//        for (int i = 0; i< ((NSArray *)self.chooseAry).count;i ++) {
//            if ([self.dataAry[i] indexOfObject:self.chooseAry[i]] != NSNotFound) {
//                [self.picker selectRow:[self.dataAry[i] indexOfObject:self.chooseAry[i]] inComponent:i animated:NO];
//            }
//        }
    }
}




#pragma mark -------action
- (void)showInView{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:self];
    self.bounds = window.bounds;
    self.frame = window.frame;
    self.center = window.center;
    self.bgView.frame = CGRectMake(0, BOUNDHEIGHT, BOUNDWIDTH, 216 + 45);
    self.bgBtn.alpha = 0;
    [UIView animateWithDuration:0.35 animations:^{
        self.bgBtn.alpha = 0.3;
        self.bgView.frame = CGRectMake(0, BOUNDHEIGHT - 216 - 45, BOUNDWIDTH, 216 + 45);
    } completion:^(BOOL finished) {
        
    }];
}
- (void)hideView{
    [UIView animateWithDuration:0.35 animations:^{
        self.bgBtn.alpha = 0;
        self.bgView.frame = CGRectMake(0, BOUNDHEIGHT, BOUNDWIDTH, 216 + 45);
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}
- (void)sureBtnAction:(UIButton *)btn{
    if (self.resultBlock) {
        if (self.viewMode == CustomPicker) {
            NSString *str = @"";
            for (int i = 0; i < self.dataAry.count; i ++) {
                NSInteger row = [self.picker selectedRowInComponent:i];
                NSArray *ary = self.dataAry[i];
                str = [str stringByAppendingString:[NSString stringWithFormat:@"%@,",ary[row]]];
            }
            str = [str substringWithRange:NSMakeRange(0, str.length - 1)];
            self.resultBlock(str);
        }
        if (self.viewMode == DatePicker) {
            self.resultBlock([self.datepicker date]);
        }
        if (self.viewMode == CustomConfirmOrderTimePicker) {
            
            NSInteger row1 = [self.picker selectedRowInComponent:0];
            NSInteger row2 = [self.picker selectedRowInComponent:1];
            
            NSString *str1;
            NSString *str2;
            if (self.data2Ary > 0) {
                if (row1 < ((NSArray *)self.dataAry[0]).count) {
                    str1 = self.dataAry[0][row1];
                }
            }
            if (row2 < self.data2Ary.count) {
                str2 = self.data2Ary[row2];
            }
            
            self.resultBlock(@{@"date":str1?:@"",@"subscribeTime":str2?:@""});
        }
    }
    [self hideView];
}


#pragma mark ----UIPickerViewDelegate,UIPickerViewDataSource
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    if (self.viewMode == CustomConfirmOrderTimePicker) {
        return 2;
    }
    return _dataAry.count;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if (self.viewMode == CustomConfirmOrderTimePicker) {
        if (component == 0) {
            return ((NSArray *)self.dataAry[0]).count;
        }else if (component == 1){
            return self.data2Ary.count;
        }
        return 0;
    }
    NSArray *ary = _dataAry[component];
    return ary.count;
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    if (self.viewMode == CustomConfirmOrderTimePicker) {
        if (component == 0) {
            return ((NSArray *)self.dataAry[0])[row];
        }else if (component == 1){
            return self.data2Ary[row];
        }
        return 0;
    }
    NSArray *ary = _dataAry[component];
    return ary[row];
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{
    if (_dataAry.count == 0) {
        return BOUNDWIDTH;
    }
    return BOUNDWIDTH / _dataAry.count;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[UILabel alloc] init];
        // Setup label properties - frame, font, colors etc
        //adjustsFontSizeToFitWidth property to YES
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        [pickerLabel setFont:FONT_SIZE(15)];
    }
    // Fill the label text here
    pickerLabel.text = [self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    if (self.viewMode == CustomConfirmOrderTimePicker) {
        if (component == 0) {
            self.data2Ary = self.dataAry[1][row];
            [self.picker reloadComponent:1];
            if (self.data2Ary.count > 0) {
                [self.picker selectRow:0 inComponent:1 animated:NO];
            }
        }
    }
}


/**
 初始化
 */
- (UIPickerView *)picker{
    if (!_picker) {
        _picker = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 0, BOUNDWIDTH, 216)];
        _picker.delegate = self;
        _picker.dataSource = self;
    }
    return _picker;
}
- (UIDatePicker *)datepicker{
    if (!_datepicker) {
        _datepicker = [[UIDatePicker alloc]initWithFrame:CGRectMake(0, 0, BOUNDWIDTH, 216)];
        _datepicker.datePickerMode = UIDatePickerModeDate;
        NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];//设置为中文
        _datepicker.locale = locale;
        NSDate *maxDate = [NSDate dateWithTimeIntervalSinceNow:3600*24*365];
        _datepicker.maximumDate = maxDate;
    }
    return _datepicker;
}
- (UIView *)bgView{
    if (!_bgView) {
        _bgView = [[UIView alloc]init];
        _bgView.backgroundColor = [UIColor whiteColor];
    }
    return _bgView;
}
- (UIButton *)bgBtn{
    if (!_bgBtn) {
        _bgBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _bgBtn.backgroundColor = [UIColor blackColor];
        [_bgBtn addTarget:self action:@selector(hideView) forControlEvents:UIControlEventTouchUpInside];
    }
    return _bgBtn;
}

- (UIButton *)sureBtn{
    if (!_sureBtn) {
        _sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_sureBtn setTitle:@"确定" forState:UIControlStateNormal];
        _sureBtn.titleLabel.font = FONT_SIZE(15);
        [_sureBtn setTitleColor:Common_TextColor forState:UIControlStateNormal];
        [_sureBtn addTarget:self action:@selector(sureBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sureBtn;
}
- (UIButton *)cancelBtn{
    if (!_cancelBtn) {
        _cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        _cancelBtn.titleLabel.font = FONT_SIZE(15);
        [_cancelBtn setTitleColor:Common_TextColor forState:UIControlStateNormal];
        [_cancelBtn addTarget:self action:@selector(hideView) forControlEvents:UIControlEventTouchUpInside];
        [_cancelBtn sizeToFit];
        _cancelBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
      
    }
    return _cancelBtn;
}
- (UILabel *)titleLab{
    if (!_titleLab) {
        _titleLab = [[UILabel alloc]init];
        _titleLab.font = FONT_SIZE(14);
        _titleLab.textColor =  Common_TextColor;
        _titleLab.textAlignment = NSTextAlignmentCenter;
    }
    return _titleLab;
}
- (NSArray *)dataAry{
    if (!_dataAry) {
        _dataAry = [[NSArray alloc]init];
    }
    return _dataAry;
}

@end
